<?php declare(strict_types=1);

namespace App\Model;

use App\Trait\ModelCacheTrait;

class Config extends \DbModels\Config
{
    public const TYPE_TEXT = 1;
    public const TYPE_IMAGE = 2;
    public const TYPE_VIDEO = 3;
    public const TYPE_OTHER = 4;

    public const TYPE_OPTIONS = [self::TYPE_TEXT, self::TYPE_IMAGE, self::TYPE_VIDEO, self::TYPE_OTHER];

    use ModelCacheTrait;

    protected static string $cacheKey = 'Cache:Configs';

    public array $cacheFields = ['id', 'label', 'value'];

    protected string $cacheKeyMap = 'MapCache:Configs';

    protected function getCacheMap(): array
    {
        $redis = getRedis();
        if ($redis->exists($this->cacheKeyMap)) {
            return $redis->hGetAll($this->cacheKeyMap);
        }
        $map = self::query()->pluck('value', 'label')->toArray();
        if (empty($map)) {
            $this->emptyCache();
        } else {
            $this->createCache($map);
        }
        return $map;
    }


    public function getVal(string $label, mixed $default = null)
    {
        $data = $this->getCacheMap();
        return $data[$label] ?? $default;
    }

    private function createCache(array $data): void
    {
        $redis = getRedis();
        $redis->hMSet($this->cacheKeyMap, $data);
        $redis->expire($this->cacheKeyMap, $this->lifespan());
    }

    private function emptyCache(): void
    {
        getRedis()->set($this->cacheKeyMap, null, $this->lifespan());
    }

    public function clearCache(): void
    {
        $this->deleteCache();
        getRedis()->del($this->property('cacheKeyMap'));
    }

}